// 窗口管理器
const { BrowserWindow } = require('electron');
const path = require('path');
const appConfig = require('../config/app-config');

class WindowManager {
    constructor() {
        this.mainWindow = null;
        this.windows = new Map();
    }

    /**
     * 创建主窗口
     */
    createMainWindow() {
        const config = appConfig.window;
        
        
        this.mainWindow = new BrowserWindow({
            width: config.defaultWidth,
            height: config.defaultHeight,
            minWidth: config.minWidth,
            minHeight: config.minHeight,
            backgroundColor: config.backgroundColor,
            show: config.show,
            titleBarStyle: 'hiddenInset',
            icon: path.join(__dirname, '../../renderer/assets/icon.png'),
            webPreferences: {
                nodeIntegration: true,
                contextIsolation: false,
                enableRemoteModule: false,
                preload: path.join(__dirname, '../preload.js'),
                webSecurity: false,
                allowRunningInsecureContent: true,
                sandbox: false
            }
        });

        // 加载应用界面
        this.mainWindow.loadFile(path.join(__dirname, '../../renderer/index.html'))
            .catch((error) => {
                console.error('[WindowManager] HTML 文件加载失败:', error);
            });

        // 监听预加载脚本执行
        this.mainWindow.webContents.on('did-finish-load', () => {
            // 页面加载完成
        });

        // 监听预加载脚本错误
        this.mainWindow.webContents.on('preload-error', (event, preloadPath, error) => {
            console.error('[WindowManager] 预加载脚本错误:', preloadPath, error);
        });

        // 窗口准备显示时的处理
        this.mainWindow.once('ready-to-show', () => {
            this.mainWindow.show();
            this.setupDevelopmentFeatures();
        });

        // 窗口关闭时的处理
        this.mainWindow.on('closed', () => {
            this.mainWindow = null;
        });

        // 处理新窗口请求
        this.mainWindow.webContents.setWindowOpenHandler(({ url }) => {
            require('electron').shell.openExternal(url);
            return { action: 'deny' };
        });

        this.windows.set('main', this.mainWindow);
        return this.mainWindow;
    }

    /**
     * 设置开发模式功能
     */
    setupDevelopmentFeatures() {
        // 注册全局快捷键来打开开发者工具（生产环境也可用）
        this.registerDevToolsShortcut();
        
        if (this.isDevelopment()) {
            const { ipcMain } = require('electron');
            const setupDevReload = require('./dev-reload').default;
            
            if (appConfig.development.devTools) {
                this.mainWindow.webContents.openDevTools();
            }
            
            if (appConfig.development.hotReload) {
                setupDevReload(this.mainWindow);
            }
        }
    }

    /**
     * 注册开发者工具快捷键
     */
    registerDevToolsShortcut() {
        const { globalShortcut } = require('electron');
        
        // 注册 Cmd+Shift+I (macOS) 或 Ctrl+Shift+I (Windows/Linux)
        const shortcut = process.platform === 'darwin' ? 'Command+Shift+I' : 'Control+Shift+I';
        
        const registered = globalShortcut.register(shortcut, () => {
            if (this.mainWindow && !this.mainWindow.isDestroyed()) {
                const isOpen = this.mainWindow.webContents.isDevToolsOpened();
                if (isOpen) {
                    this.mainWindow.webContents.closeDevTools();
                } else {
                    this.mainWindow.webContents.openDevTools();
                }
            }
        });

        if (registered) {
            console.log(`[WindowManager] 开发者工具快捷键已注册: ${shortcut}`);
        } else {
            console.warn(`[WindowManager] 开发者工具快捷键注册失败: ${shortcut}`);
        }

        // 应用退出时取消注册
        require('electron').app.on('will-quit', () => {
            globalShortcut.unregister(shortcut);
        });
    }

    /**
     * 检查是否为开发模式
     */
    isDevelopment() {
        return process.argv.includes('--dev') || process.env.NODE_ENV === 'development';
    }

    /**
     * 获取主窗口
     */
    getMainWindow() {
        return this.mainWindow;
    }

    /**
     * 关闭所有窗口
     */
    closeAllWindows() {
        this.windows.forEach((window, id) => {
            if (!window.isDestroyed()) {
                window.close();
            }
        });
        this.windows.clear();
    }
}

module.exports = new WindowManager();
